﻿using chihuopig.DTO;
using chihuopig.IService;
using chihuopig.Model;
using chihuopig.Tool;
using chihuopig.Web.Framework;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Text;
using System.Threading.Tasks;
//using Senparc.Weixin.mp

namespace chihuopig.Web.Controllers
{
    public class HomeController : WebViewController
    {
        IArticleService _iArticleService;
        IDatabase _iDatabase;
        public HomeController
        (
            IArticleService iarticleService,
           IDatabase iDatabase
        )
        {
            _iArticleService = iarticleService;
           _iDatabase=iDatabase;
        }
        [AdminMenuFilter("123")]
        public async Task<IActionResult> Index(int pageIndex=1, int PageSize=25,bool IsAjax=false)
        {

            //StringBuilder sb = new StringBuilder();
            //_MemcachedClient.Remove(CacheHelper.HomeIndexCacheKey);
            ReturnJson mo = null;
            //mo = new ReturnJson();
            //var data = await _iArticleService.GetPage(pageIndex, PageSize);
            //var PageTotalJson = await _iArticleService.GetPageTotal(PageSize);
            //mo.Data = JsonConvert.SerializeObject(data);
            //mo.Total = "{\"Total\":" + PageTotalJson + "}";
            //_iDatabase.TransactionQueued()
            //_iDatabase.KeyDelete(CacheHelper.HomeIndexCacheKey);
            //IGetOperationResult<ReturnJson> ReturnJsondata = await _MemcachedClient.GetAsync<ReturnJson>(CacheHelper.HomeIndexCacheKey);
            if (IsAjax)
            {
                var data = await _iArticleService.GetPage(pageIndex, PageSize);
                return Json(data);
            }

            if (!_iDatabase.KeyExists(CacheHelper.HomeIndexCacheKey(1)))
            {

                mo = new ReturnJson();
                var data = await _iArticleService.GetPage(pageIndex, PageSize);
                var PageTotalJson = await _iArticleService.GetPageTotal(PageSize);
                mo.Data = JsonConvert.SerializeObject(data);
                mo.Total = "{\"Total\":" + PageTotalJson + "}";
                await _iDatabase.StringSetAsync(CacheHelper.HomeIndexCacheKey(1), JsonConvert.SerializeObject(mo));
            }
            else
            {
                var str = await _iDatabase.StringGetAsync(CacheHelper.HomeIndexCacheKey(1));
                mo = JsonConvert.DeserializeObject<ReturnJson>(str);

            }

            return View(mo);
        }



        public IActionResult detail()
        {

           //ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View();
        }

      
     
        
    }
}
